﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Pipes;
using System.Threading;
using System.IO;
using LogLib;
using Newtonsoft.Json;

namespace CardQCProcessor
{
    /// <summary>
    /// 照片检测服务器
    /// </summary>
    public class CardPhotoQCServer
    {
        public event Func<string, string> Checking;
       
        private NamedPipeServerStream Server { get; set; }     
       
        private StringBuilder InputStr { get; set; }
        
        private bool _running = true;
       
        public CardPhotoQCServer(string name)
        {
            this.Server = new NamedPipeServerStream(
                name,
                PipeDirection.InOut,
                1,
                PipeTransmissionMode.Message,
                PipeOptions.None);
            this.InputStr = new StringBuilder();
        }

        public void Start()
        {
            _running = true;
            while (_running)
            {
                Program.TraceWorkingState("一所质检服务准备就绪，等待客户端连接中...");            
                this.Server.WaitForConnection();
                Program.TraceWorkingState("和客户端连接成功，准备接收传入的数据...");
                StreamString ss = new StreamString(this.Server);
                this.InputStr.Append(ss.ReadString());               
                Program.TraceWorkingState("数据接收完毕，开始处理...");              
                //获取输出字符串
                string outStr = "";
                string InputString = this.InputStr.ToString().Trim();
                if (Checking != null)
                {
                    outStr = this.Checking.Invoke(InputString).Trim();
                }
                this.InputStr.Clear();
                Program.TraceWorkingState("数据处理完成，准备返回结果...");
                ss.WriteString(outStr);
                Server.WaitForPipeDrain();
                Server.Disconnect();
                Program.TraceWorkingState("连接关闭.");
            }
        }

        public void Stop()
        {
            _running = false;
        }
    }
}
